package com.example.codedemo.slice;

import com.example.codedemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.qrcode.IBarcodeDetector;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class MainAbilitySlice extends AbilitySlice {
    ConnectionCallback connectionCallback;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Image image = (Image) findComponentById(ResourceTable.Id_image);
        connectionCallback = new ConnectionCallback() {
            @Override
            public void onServiceConnect() {
                IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(MainAbilitySlice.this);
                byte[] bytes = new byte[152 * 152 * 4];
                barcodeDetector.detect("二维码内容", bytes, 152, 152);
                InputStream inputStream = new ByteArrayInputStream(bytes);
                ImageSource imageSource = ImageSource.create(inputStream,null);
                ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
                PixelMap pixelMap = imageSource.createPixelmap(decodingOpts);
                image.setPixelMap(pixelMap);
                barcodeDetector.release();
                VisionManager.destroy();
            }

            @Override
            public void onServiceDisconnect() {

            }
        };
        // 通过code可以获取方法的调用结果
        int code = VisionManager.init(this, connectionCallback);

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
